package com.alisls.demo.springcloud.oauth.server.service.impl;

import com.alisls.demo.springcloud.common.core.exception.BizException;
import com.alisls.demo.springcloud.oauth.server.dao.OAuthClientDetailDAO;
import com.alisls.demo.springcloud.oauth.server.dto.OAuthClientDetailDTO;
import com.alisls.demo.springcloud.oauth.server.dto.OAuthClientDetailPwdDTO;
import com.alisls.demo.springcloud.oauth.server.entity.OAuthClientDetailDO;
import com.alisls.demo.springcloud.oauth.server.service.OAuthClientDetailService;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * OAuth客户端服务
 *
 * @author Ke Wang
 * @date 2020/10/31
 */
@Service("oAuthClientDetailService")
@AllArgsConstructor
public class OAuthClientDetailServiceImpl implements OAuthClientDetailService {

    private final PasswordEncoder passwordEncoder;

    private final OAuthClientDetailDAO authClientDetailDAO;

    /**
     * 根据ClientId查询OAuth客户端
     * @param clientId 客户端id
     * @return OAuthClientDetailDTO
     */
    @Override
    public OAuthClientDetailDTO getByClientId(String clientId) {
        OAuthClientDetailDTO oAuthClientDetailDTO = new OAuthClientDetailDTO();

        OAuthClientDetailDO oAuthClientDetailDO = authClientDetailDAO.selectById(clientId);
        if (oAuthClientDetailDO != null) {
            BeanUtils.copyProperties(oAuthClientDetailDO, oAuthClientDetailDTO);
        }

        return oAuthClientDetailDTO;
    }

    /**
     * 保存OAuth客户端
     * @param oAuthClientDetailPwdDTO 带密码的OAuth客户端
     * @return OAuthClientDetailDTO
     */
    @Override
    public OAuthClientDetailDTO save(OAuthClientDetailPwdDTO oAuthClientDetailPwdDTO) {
        OAuthClientDetailDO oAuthClientDetailDO = new OAuthClientDetailDO();
        BeanUtils.copyProperties(oAuthClientDetailPwdDTO, oAuthClientDetailDO);

        // 对原始密码进行加密
        String password = oAuthClientDetailPwdDTO.getClientSecret();
        password = passwordEncoder.encode(password);
        oAuthClientDetailDO.setClientSecret(password);

        int insertNum = authClientDetailDAO.insert(oAuthClientDetailDO);
        if (insertNum <= 0) {
            throw new BizException("保存OAuthClientDetail失败！");
        }
        return oAuthClientDetailPwdDTO;
    }

    @Override
    public Integer remove(String clientId) {
        return authClientDetailDAO.deleteById(clientId);
    }


}
